package org.jeecg.modules.smoke.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.smoke.entity.LwgyJointSmokeAlarm;
import org.jeecg.modules.smoke.entity.LwgyJointSmokeConfiguration;
import org.jeecg.modules.smoke.service.ILwgyJointSmokeAlarmService;
import org.jeecg.modules.smoke.service.ILwgyJointSmokeConfigurationService;
import org.jeecg.modules.water.entity.LwgyJointWater;
import org.jeecg.modules.water.entity.LwgyJointWaterConfiguration;
import org.jeecg.modules.water.service.ILwgyJointWaterConfigurationService;
import org.jeecg.modules.water.service.ILwgyJointWaterService;
import org.jeecg.modules.water.service.ILwgyRelaxConnectionService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class SysnSmokeStateJob implements Job {


    @Autowired
    private ILwgyJointSmokeAlarmService lwgyJointSmokeAlarmService;
    @Autowired
    private ILwgyJointSmokeConfigurationService lwgyJointSmokeConfigurationService;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //所有设备
        List<LwgyJointSmokeConfiguration> allDevices = getAllDevices();
        //最近1分钟在线设备
        List<LwgyJointSmokeAlarm> recentAlarms = getRecentAlarms();

        if(allDevices.size()>0){
            if(recentAlarms.size()>0){
                // 获取在线设备号
                Set<String> onlineDeviceNumbers = recentAlarms.stream()
                        .map(LwgyJointSmokeAlarm::getDeviceNumber)
                        .collect(Collectors.toSet());
                // 筛选不在线的设备 ,,并筛选设备状态为 "0" 的修改为1（不在线）
                List<LwgyJointSmokeConfiguration> offlineDevices = allDevices.stream()
                        .filter(device -> !onlineDeviceNumbers.contains(device.getDeviceNumber()) && "0".equals(device.getOnlineState()))
                        .collect(Collectors.toList());
                //保存状态修改 在线修改为不在线
                if(offlineDevices.size()>0){
                    System.out.println("待修改的不在线设备数量："+offlineDevices.size());
                    updateDeviceStatuses(offlineDevices,"1");//吧不在线的设备修改为离线
                }

                // Step 2:筛选在线的设备 ,并筛选设备状态为 "1" 的修改为0（在线）
                QueryWrapper<LwgyJointSmokeConfiguration> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("device_number", onlineDeviceNumbers)
                        .eq("online_state", "1");
                List<LwgyJointSmokeConfiguration> devicesToUpdate = lwgyJointSmokeConfigurationService.list(queryWrapper);
                //保存状态修改 离线修改为在线
                if(devicesToUpdate.size()>0){
                    System.out.println("待修改的在线设备数量："+devicesToUpdate.size());
                    updateDeviceStatuses(devicesToUpdate,"0");//吧在线的设备修改为在线
                }

            }else{
                //所有的设备都不在线
                updateDeviceStatuses(allDevices,"1");//吧不在线的设备修改为离线
            }







        }


    }

    public List<LwgyJointSmokeConfiguration> getAllDevices() {
        // 查询所有设备配置
        QueryWrapper<LwgyJointSmokeConfiguration> configurationQueryWrapper = new QueryWrapper<>();
        configurationQueryWrapper.isNotNull("device_number");
        return lwgyJointSmokeConfigurationService.list(configurationQueryWrapper);
    }

    public List<LwgyJointSmokeAlarm> getRecentAlarms() {
        LocalDateTime oneMinuteAgo = LocalDateTime.now().minusMinutes(1);
        QueryWrapper<LwgyJointSmokeAlarm> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("create_time", oneMinuteAgo);
        List<LwgyJointSmokeAlarm> alarms = lwgyJointSmokeAlarmService.list(queryWrapper);

        // 按设备号去重
        Map<String, LwgyJointSmokeAlarm> distinctAlarms = alarms.stream()
                .collect(Collectors.toMap(
                        LwgyJointSmokeAlarm::getDeviceNumber,
                        alarm -> alarm,
                        (existing, replacement) -> existing
                ));

        return new ArrayList<>(distinctAlarms.values());
    }

    public void updateDeviceStatuses(List<LwgyJointSmokeConfiguration> devicesToUpdate,String state) {
        UpdateWrapper<LwgyJointSmokeConfiguration> updateWrapper = new UpdateWrapper<>();
        for (LwgyJointSmokeConfiguration device : devicesToUpdate) {
            updateWrapper.eq("device_number", device.getDeviceNumber())
                    .set("online_state", state);
        }
        lwgyJointSmokeConfigurationService.update(null, updateWrapper);
    }
}









